package com.rgs.oauthresource2.demos.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

/**
 * @author RenGaoshuai
 * @date 2024/4/10 10:31
 * @description 资源服务器配置类
 *
 * 作为资源服务的配置类必须满足两个条件，如下：
 *
 * 标注注解@EnableResourceServer  标注是一个资源服务
 * 继承ResourceServerConfigurerAdapter
 * @EnableGlobalMethodSecurity 开启注解校验权限
 */
@Configurable
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        //check_token校验的端点
        tokenService.setCheckTokenEndpointUrl("http://localhost:2003/oauth/check_token");
        //唯一id
        tokenService.setClientId("myjszl");
        //密钥
        tokenService.setClientSecret("123");
        return tokenService;
    }


    //配置资源id 和 token校验服务
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("res1")
                .tokenServices(tokenService());
    }

    //配置 security安全策略
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // oauth2.hasScope 校验客户端权限。
        http.authorizeRequests()
//                .antMatchers("/**").permitAll()
                //所有路径都需要all权限
                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated();
    }
}
